/*
 * @Author: your name
 * @Date: 2021-11-30 09:59:47
 * @LastEditTime: 2021-12-03 10:50:41
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \express-app\utils\upload.js
 */

const multer = require('multer');
const sd = require('silly-datetime');
const path = require('path');
const mkdirp = require('mkdirp');
module.exports = {
  upload() {
    const storage = multer.diskStorage({
      //配置上传的目录
      destination: async (req, file, cb) => {
        let day = sd.format(new Date(), 'YYYY-MM-DD');
        let dir = path.join('public/uploadfiles', day);
        await mkdirp(dir); //创建、读取、删除、请求文件 操作数据库，操作文件，网络请求下载 I/O操作 都是异步！
        cb(null, dir);
      },
      //配置文件名
      filename: function (req, file, cb) {
        // const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        // cb(null, file.fieldname + '-' + uniqueSuffix)
        const uniqueSuffix = path.extname(file.originalname);
        cb(null, Date.now() + uniqueSuffix);
      },
    });
    const upload = multer({ storage: storage });
    return upload;
  },
};
